package com.xmy.cultivate.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.IdWorker;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 教师权限表 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2025-05-10
 */
@RestController
@RequestMapping("/api/authAllotTeacher")
public class AuthAllotTeacherController extends BaseController{

    @Autowired
    IAuthAllotTeacherService iAuthAllotTeacherService;

    @Autowired
    IStaffService iStaffService;

    @Autowired
    IMobilePermissionService iMobilePermissionService;

    @Autowired
    IAuthAllotTeacherProjectsService iAuthAllotTeacherProjectsService;

    @Autowired
    IAuthAllotTeacherSchoolService iAuthAllotTeacherSchoolService;

    @Autowired
    IdWorker idWorker;

    @Autowired
    IOrganizationService iOrganizationService;

    @Autowired
    IMobileStaffPermissionService iMobileStaffPermissionService;

    @Autowired
    IQyWeChartPushService iQyWeChartPushService;

    @Autowired
    IRecruitPushLogService iRecruitPushLogService;

    /**
     * 分配权限列表
     * @param pageNum
     * @param pageSize
     * @param teacherName
     * @return
     */

    @GetMapping("/getAuthAllotTeacherList")
    public Result getAuthAllotTeacherList(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                              @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize,
                              @RequestParam(name = "teacherName", required = false) String teacherName){
        IPage<AuthAllotTeacher> iPage = new Page<>(pageNum, pageSize);
        iAuthAllotTeacherService.getAuthAllotTeacherList(iPage,this.adminId,teacherName);
        return new Result(Code.OK,new PageResult(iPage.getRecords(),iPage.getTotal(),iPage.getPages()));
    }

    /**
     * 获取教师
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/teacherList")
    public Result teacherList(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                              @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize,
                              @RequestParam(name = "teacherName", required = false) String teacherName){
        IPage<Staff> iPage = new Page<>( pageNum, pageSize);
        QueryWrapper<Staff> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted",0);
        queryWrapper.eq("status",1);
        queryWrapper.like(StringUtils.isNotBlank(teacherName),"name",teacherName);
        iPage = iStaffService.page(iPage,queryWrapper);
        return new Result(Code.OK,new PageResult(iPage.getRecords(),iPage.getTotal(),iPage.getPages()));
    }

    /**
     * 获取功能权限
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/mobilePermissionList")
    public Result mobilePermissionList(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                              @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize,
                              @RequestParam(name = "name", required = false) String name){
        IPage<MobilePermission> iPage = new Page<>( pageNum, pageSize);
        QueryWrapper<MobilePermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("level",3);
        queryWrapper.eq("data_type",1);
        queryWrapper.like(StringUtils.isNotBlank(name),"name",name);
        List<Long> permissList = iMobileStaffPermissionService.getStaffPermissionAllIdByStaffId(this.adminId,1);////菜单权限
        if (permissList != null && permissList.size() > 0){
            queryWrapper.in("id",permissList);
        }
        iPage = iMobilePermissionService.page(iPage,queryWrapper);
        return new Result(Code.OK,new PageResult(iPage.getRecords(),iPage.getTotal(),iPage.getPages()));
    }


    @PostMapping("/addAuthAllotTeacher")
    @Transactional(rollbackFor = Exception.class)
    public Result addAuthAllotTeacher(@RequestBody Map reMap){
        try {

            if (reMap.get("list") != null && !Objects.equals(reMap.get("list").toString(), "")) {
                List<Object> rsList = (List<Object>) reMap.get("list");
                for (Object object : rsList) {

                    String jsonObjectList = JSON.toJSONString(object);
                    AuthAllotTeacher authAllotTeacher = JSONObject.parseObject(jsonObjectList, AuthAllotTeacher.class);
                    authAllotTeacher.setId(idWorker.nextId());
                    iAuthAllotTeacherService.save(authAllotTeacher);

                    List<AuthAllotTeacherProjects> authAllotTeacherProjectsList = authAllotTeacher.getAuthAllotTeacherProjectsList();
                    if (authAllotTeacherProjectsList != null && !authAllotTeacherProjectsList.isEmpty()) {

                        for (AuthAllotTeacherProjects authAllotTeacherProjects : authAllotTeacherProjectsList) {
                            authAllotTeacherProjects.setId(idWorker.nextId());
                            authAllotTeacherProjects.setAuthTeacherId(authAllotTeacher.getId());
                        }
                        //批量保存功能权限
                        iAuthAllotTeacherProjectsService.saveBatch(authAllotTeacherProjectsList);
                    }
                    AuthAllotTeacherSchool authAllotTeacherSchool = authAllotTeacher.getAuthAllotTeacherSchool();
                    if (authAllotTeacherSchool != null) {
                        authAllotTeacherSchool.setId(idWorker.nextId());
                        authAllotTeacherSchool.setAuthTeacherId(authAllotTeacher.getId());
                        iAuthAllotTeacherSchoolService.save(authAllotTeacherSchool);
                    }
                    //推送
                    Staff staff = iStaffService.getById(authAllotTeacher.getTeacherId());
                    if (staff != null){
                        if (StringUtils.isNotBlank(staff.getQyWecharId())) {
                            String pushTitle = "权限分配";
                            String content = "负责人给您开通了权限，您有新增可查看的数据";
                            //权限分配推送
                            iQyWeChartPushService.push(staff.getQyWecharId(),pushTitle,content,null,4,authAllotTeacher.getTeacherId());

                        }else {
                            RecruitPushLog log = new RecruitPushLog();
//                            log.setRecruitId(tryJob.getRecruitId());
                            log.setType(3);
                            log.setPushStaffId(authAllotTeacher.getTeacherId());
                            log.setStatus(0); //0未推送
                            log.setRemark(staff.getName()+"qyWecharId为空");
                            iRecruitPushLogService.save(log);

                        }
                    }

                }
            }
            return new Result(Code.SAVE_OK, "", "保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.SAVE_ERROR, "", "保存失败");
        }
    }



    @PutMapping("/editAuthAllotTeacher")
    @Transactional(rollbackFor = Exception.class)
    public Result editAuthAllotTeacher(@RequestBody Map reMap){
        try {

            if (reMap.get("list") != null && !Objects.equals(reMap.get("list").toString(), "")) {
                List<Object> rsList = (List<Object>) reMap.get("list");
                for (Object object : rsList) {

                    String jsonObjectList = JSON.toJSONString(object);
                    AuthAllotTeacher authAllotTeacher = JSONObject.parseObject(jsonObjectList, AuthAllotTeacher.class);

                    AuthAllotTeacher authAllotTeacher1 = iAuthAllotTeacherService.getById(authAllotTeacher.getId());
                    if (authAllotTeacher1 == null){
                        return new Result(Code.SAVE_ERROR, "", "数据不存在");
                    }

                    //删除功能权限
                    QueryWrapper<AuthAllotTeacherProjects> objectQueryWrapper = new QueryWrapper<>();
                    objectQueryWrapper.eq("auth_teacher_id", authAllotTeacher.getId());
                    iAuthAllotTeacherProjectsService.remove(objectQueryWrapper);

                    //删除学校权限
                    QueryWrapper<AuthAllotTeacherSchool> schoolQueryWrapperSchool = new QueryWrapper<>();
                    schoolQueryWrapperSchool.eq("auth_teacher_id", authAllotTeacher.getId());
                    iAuthAllotTeacherSchoolService.remove(schoolQueryWrapperSchool);

                    //删除学校权限
                    QueryWrapper<AuthAllotTeacher> teacherQueryWrapper = new QueryWrapper<>();
                    teacherQueryWrapper.eq("id", authAllotTeacher.getId());
                    iAuthAllotTeacherService.remove(teacherQueryWrapper);



                    authAllotTeacher.setId(idWorker.nextId());
                    iAuthAllotTeacherService.save(authAllotTeacher);
                    List<AuthAllotTeacherProjects> authAllotTeacherProjectsList = authAllotTeacher.getAuthAllotTeacherProjectsList();
                    if (authAllotTeacherProjectsList != null && !authAllotTeacherProjectsList.isEmpty()) {

                        for (AuthAllotTeacherProjects authAllotTeacherProjects : authAllotTeacherProjectsList) {
                            authAllotTeacherProjects.setId(idWorker.nextId());
                            authAllotTeacherProjects.setAuthTeacherId(authAllotTeacher.getId());
                        }
                        //批量保存功能权限
                        iAuthAllotTeacherProjectsService.saveBatch(authAllotTeacherProjectsList);
                    }
                    AuthAllotTeacherSchool authAllotTeacherSchool = authAllotTeacher.getAuthAllotTeacherSchool();
                    if (authAllotTeacherSchool != null) {
                        authAllotTeacherSchool.setId(idWorker.nextId());
                        authAllotTeacherSchool.setAuthTeacherId(authAllotTeacher.getId());
                        iAuthAllotTeacherSchoolService.save(authAllotTeacherSchool);
                    }
                }
            }
            return new Result(Code.SAVE_OK, "", "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.SAVE_ERROR, "", "修改失败");
        }
    }


  /*  @PostMapping("/addAuthAllotTeacher")
    @Transactional(rollbackFor = Exception.class)
    public Result addAuthAllotTeacher(@RequestBody List<AuthAllotTeacher> authAllotTeachersr){
        if (authAllotTeachersr == null || authAllotTeachersr.isEmpty()) {
            return new Result(Code.SAVE_ERROR, "", "数据为空，请填写数据");
        }
        try {
            for (AuthAllotTeacher authAllotTeacher : authAllotTeachersr) {
                authAllotTeacher.setId(idWorker.nextId());
                authAllotTeacher.setCreatedId(this.adminId);
                iAuthAllotTeacherService.save(authAllotTeacher);

                List<AuthAllotTeacherProjects> authAllotTeacherProjectsList = authAllotTeacher.getAuthAllotTeacherProjectsList();
                if (authAllotTeacherProjectsList != null && !authAllotTeacherProjectsList.isEmpty()) {

                    for (AuthAllotTeacherProjects authAllotTeacherProjects : authAllotTeacherProjectsList) {
                        authAllotTeacherProjects.setId(idWorker.nextId());
                        authAllotTeacherProjects.setAuthTeacherId(authAllotTeacher.getId());
                    }
                    //批量保存功能权限
                    iAuthAllotTeacherProjectsService.saveBatch(authAllotTeacherProjectsList);
                }
                AuthAllotTeacherSchool authAllotTeacherSchool = authAllotTeacher.getAuthAllotTeacherSchool();
                if (authAllotTeacherSchool != null) {
                    authAllotTeacherSchool.setId(idWorker.nextId());
                    authAllotTeacherSchool.setAuthTeacherId(authAllotTeacher.getId());
                    iAuthAllotTeacherSchoolService.save(authAllotTeacherSchool);
                }
            }
            return new Result(Code.SAVE_OK, "", "保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.SAVE_ERROR, "", "保存失败");
        }
    }*/

//    @PostMapping("/editAuthAllotTeacher")
//    @Transactional(rollbackFor = Exception.class)
//    public Result editAuthAllotTeacher(@RequestBody AuthAllotTeacher authAllotTeacher) {
//        if (authAllotTeacher == null || authAllotTeacher.getId() == null) {
//            return new Result(Code.SAVE_ERROR, "", "请填写要编辑的信息");
//        }
//        try {
//            AuthAllotTeacher authAllotTeacher1 = iAuthAllotTeacherService.getById(authAllotTeacher.getId());
//            if (authAllotTeacher1 == null){
//                return new Result(Code.SAVE_ERROR, "", "数据不存在");
//            }
//            iAuthAllotTeacherService.updateById(authAllotTeacher);
//            //删除功能权限
//            QueryWrapper<AuthAllotTeacherProjects> objectQueryWrapper = new QueryWrapper<>();
//            objectQueryWrapper.eq("auth_teacher_id", authAllotTeacher.getId());
//            iAuthAllotTeacherProjectsService.remove(objectQueryWrapper);
//
//            //删除学校权限
//            QueryWrapper<AuthAllotTeacherSchool> schoolQueryWrapperchool = new QueryWrapper<>();
//            schoolQueryWrapperchool.eq("auth_teacher_id", authAllotTeacher.getId());
//            iAuthAllotTeacherSchoolService.remove(schoolQueryWrapperchool);
//
//
//            List<AuthAllotTeacherProjects> authAllotTeacherProjectsList = authAllotTeacher.getAuthAllotTeacherProjectsList();
//            if (authAllotTeacherProjectsList != null && !authAllotTeacherProjectsList.isEmpty()){
//                for (AuthAllotTeacherProjects authAllotTeacherProjects : authAllotTeacherProjectsList) {
//                    //修改功能权限
//                    iAuthAllotTeacherProjectsService.updateById(authAllotTeacherProjects);
//                }
//            }
//            AuthAllotTeacherSchool authAllotTeacherSchool = authAllotTeacher.getAuthAllotTeacherSchool();
//            if (authAllotTeacherSchool != null) {
//                //修改学校权限
//                iAuthAllotTeacherSchoolService.updateById(authAllotTeacherSchool);
//            }
//
//            return new Result(Code.UPDATE_OK, "", "修改成功");
//        }  catch (Exception e) {
//            e.printStackTrace();
//            return new Result(Code.UPDATE_ERROR, "", "修改失败");
//        }
//    }


    /**
     * 详情
     * @return
     */
    @GetMapping("/details")
    public Result details(@RequestParam(value = "id") Long id){
        AuthAllotTeacher authAllotTeacher = iAuthAllotTeacherService.getById(id);

        if (authAllotTeacher == null){
            return new Result(Code.GET_ERROR, "", "数据不存在");
        }
        Staff staff = iStaffService.getById(authAllotTeacher.getTeacherId());
        if (staff != null){
            authAllotTeacher.setTeacherName(staff.getName());
        }

        QueryWrapper<AuthAllotTeacherSchool> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("auth_teacher_id",id);
        queryWrapper.eq("deleted",0);
        AuthAllotTeacherSchool authAllotTeacherSchool = iAuthAllotTeacherSchoolService.getOne(queryWrapper);

        if (authAllotTeacherSchool != null){
            String schoolIdsStr = authAllotTeacherSchool.getSchoolIds();
            List<Long> schoolIdList = Arrays.stream(schoolIdsStr.split(","))
                    .map(String::trim)
                    .map(Long::valueOf)
                    .collect(Collectors.toList());

            QueryWrapper<Organization> organizationQueryWrapper = new QueryWrapper<>();
            organizationQueryWrapper.in("id",schoolIdList);
            List<Organization> organizationList = iOrganizationService.list(organizationQueryWrapper);

            if (organizationList != null && !organizationList.isEmpty()){
                List<String> schoolNames = organizationList.stream()
                        .map(Organization::getName)
                        .collect(Collectors.toList());
                String schoolNameStr = String.join(",", schoolNames);
                authAllotTeacherSchool.setSchoolName(schoolNameStr);
            }

            authAllotTeacher.setAuthAllotTeacherSchool(authAllotTeacherSchool);
        }
        QueryWrapper<AuthAllotTeacherProjects> ProjectsQueryWrapper = new QueryWrapper<>();
        ProjectsQueryWrapper.eq("auth_teacher_id",id);
        ProjectsQueryWrapper.eq("deleted",0);
        List<AuthAllotTeacherProjects> authAllotTeacherProjectsList = iAuthAllotTeacherProjectsService.list(ProjectsQueryWrapper);
        if (authAllotTeacherProjectsList != null && !authAllotTeacherProjectsList.isEmpty()){
            for (AuthAllotTeacherProjects authAllotTeacherProjects : authAllotTeacherProjectsList){
                MobilePermission mobilePermission = iMobilePermissionService.getById(authAllotTeacherProjects.getProjectsId());
                if (mobilePermission != null){
                    authAllotTeacherProjects.setProjectsName(mobilePermission.getName());
                }

            }
            authAllotTeacher.setAuthAllotTeacherProjectsList(authAllotTeacherProjectsList);
        }

      return new Result(Code.GET_OK, authAllotTeacher, "获取成功");
    }


    @DeleteMapping("/delete")
    @Transactional(rollbackFor = Exception.class)
    public Result delete(@RequestBody Map reMap) {
        List<String> ids = (List<String>) reMap.get("ids");
        if (ids == null || ids.isEmpty()){
            return new Result(Code.DELETE_ERROR, "", "请选择要删除的id");
        }
        try {
            for (String id : ids){
                QueryWrapper<AuthAllotTeacherSchool> queryWrapper = new QueryWrapper<>();
                queryWrapper.in("auth_teacher_id",id);
                iAuthAllotTeacherSchoolService.remove(queryWrapper);

                QueryWrapper<AuthAllotTeacherProjects> projectsQueryWrapper = new QueryWrapper<>();
                projectsQueryWrapper.in("auth_teacher_id",id);
                iAuthAllotTeacherProjectsService.remove(projectsQueryWrapper);
            }
            iAuthAllotTeacherService.removeByIds(ids);
            return new Result(Code.DELETE_OK, "", Code.DELETE_OK_MSG);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.DELETE_ERROR, "", Code.DELETE_ERROR_MSG);
        }
    }


}
